package com.xm.util.excel;

import com.xm.pojo.FlowDailyReport;
import com.xm.pojo.FlowHistory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lee on 2017/9/1.
 */
public class ExcelUtils {
    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel
    /*************************************文件上传****************************/
    public static  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                //行为空或者字段名那行
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    li.add(cell.getStringCellValue());
                }
                list.add(li);
            }
        }
//        work.close();
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }
    /*--------------------------------------导入结束-----------------------------------------------*/
    /*--------------------------------------导出开始-----------------------------------------------*/

    /**
     * 流量日报表导出公共方法
     * @param clazz
     * @param objs
     * @param map
     * @param sheetName
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     * @throws IntrospectionException
     * @throws ParseException
     */
    public static SXSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<FlowDailyReport>> map, String sheetName) throws IllegalArgumentException,IllegalAccessException,
            InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException {
        // 创建新的Excel 工作簿
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        SXSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        createTableHeader(sheet, map);//创建标题（头）
        createTableRows(sheet, map, objs, clazz);//创建内容
        return workbook;
    }

    /**
     * 历史流量数据表导出公共方法
     * @param clazz
     * @param objs
     * @param map
     * @param sheetName
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws ClassNotFoundException
     * @throws IntrospectionException
     * @throws ParseException
     */
    public static SXSSFWorkbook createFlowHistoryExcelFile(Class clazz, List objs, Map<Integer, List<FlowHistory>> map, String sheetName) throws IllegalArgumentException,IllegalAccessException,
            InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException {
        // 创建新的Excel 工作簿
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        SXSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        createFlowHistoryTableHeader(sheet, map);//创建标题（头）
        createFlowHistoryTableRows(sheet, map, objs, clazz);//创建内容
        return workbook;
    }
    /**
     * 创建表中每个列的列名
     * */
    public static final void createTableHeader(SXSSFSheet sheet, Map<Integer, List<FlowDailyReport>> map) {
        int startIndex=0;//cell起始位置
        int endIndex=0;//cell终止位置

        for (Map.Entry<Integer, List<FlowDailyReport>> entry : map.entrySet()) {
            SXSSFRow row = sheet.createRow(entry.getKey());
            List<FlowDailyReport> excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                //合并单元格
                if(excels.get(x).getCols()>1){
                    if(x==0){
                        endIndex+=excels.get(x).getCols()-1;
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }else{
                        endIndex+=excels.get(x).getCols();
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }
                    SXSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
                    cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
                    }
                }else{

                    SXSSFCell cell = row.createCell(x);
                    cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
                    }
                }
            }
        }
    }
    /**
     * 创建表的每行
     * */
    public static void createTableRows(SXSSFSheet sheet, Map<Integer, List<FlowDailyReport>> map, List objs, Class clazz)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
            ClassNotFoundException, ParseException {

        int rowindex = map.size();
        int maxKey = 0;
        List<FlowDailyReport> ems = new ArrayList<>();
        for (Map.Entry<Integer, List<FlowDailyReport>> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);

        List<Integer> widths = new ArrayList<Integer>(ems.size());
        for (Object obj : objs) {
            SXSSFRow row = sheet.createRow(rowindex);
            for (int i = 0; i < ems.size(); i++) {
                FlowDailyReport em = (FlowDailyReport) ems.get(i);
                // 获得get方法
                PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object rtn = getMethod.invoke(obj);
                String value = "";
                SXSSFCell cell = row.createCell(i);
                if (rtn==null){
                    cell.setCellValue(value);
                }else {
                    value = rtn.toString();
                    cell.setCellValue(value);
                }
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                // 获得最大列宽
                int width = value.getBytes().length * 300;
                // 还未设置，设置当前
                if (widths.size() <= i) {
                    widths.add(width);
                    continue;
                }
                // 比原来大，更新数据
                if (width > widths.get(i)) {
                    widths.set(i, width);
                }
            }
            rowindex++;
        }
        // 设置列宽
        for (int index = 0; index < widths.size(); index++) {
            Integer width = widths.get(index);
            width = width < 2500 ? 2500 : width + 300;
            width = width > 10000 ? 10000 + 300 : width + 300;
            sheet.setColumnWidth(index, width);
        }
    }

    /**
     * 创建表中每个列的列名(FlowHistory)
     * */
    public static final void createFlowHistoryTableHeader(SXSSFSheet sheet, Map<Integer, List<FlowHistory>> map) {
        int startIndex=0;//cell起始位置
        int endIndex=0;//cell终止位置

        for (Map.Entry<Integer, List<FlowHistory>> entry : map.entrySet()) {
            SXSSFRow row = sheet.createRow(entry.getKey());
            List<FlowHistory> excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                //合并单元格
                if(excels.get(x).getCols()>1){
                    if(x==0){
                        endIndex+=excels.get(x).getCols()-1;
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }else{
                        endIndex+=excels.get(x).getCols();
                        CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
                        sheet.addMergedRegion(range);
                        startIndex+=excels.get(x).getCols();
                    }
                    SXSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
                    cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
                    }
                }else{

                    SXSSFCell cell = row.createCell(x);
                    cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
                    if (excels.get(x).getCellStyle() != null) {
                        cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
                    }
                }
            }
        }
    }
    /**
     * 创建表的每行(FlowHistory)
     * */
    public static void createFlowHistoryTableRows(SXSSFSheet sheet, Map<Integer, List<FlowHistory>> map, List objs, Class clazz)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
            ClassNotFoundException, ParseException {

        int rowindex = map.size();
        int maxKey = 0;
        List<FlowHistory> ems = new ArrayList<>();
        for (Map.Entry<Integer, List<FlowHistory>> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);

        List<Integer> widths = new ArrayList<Integer>(ems.size());
        for (Object obj : objs) {
            SXSSFRow row = sheet.createRow(rowindex);
            for (int i = 0; i < ems.size(); i++) {
                FlowHistory em = (FlowHistory) ems.get(i);
                // 获得get方法
                PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object rtn = getMethod.invoke(obj);
                String value = "";
                SXSSFCell cell = row.createCell(i);
                if (rtn==null){
                    cell.setCellValue(value);
                }else {
                    value = rtn.toString();
                    cell.setCellValue(value);
                }
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                // 获得最大列宽
                int width = value.getBytes().length * 300;
                // 还未设置，设置当前
                if (widths.size() <= i) {
                    widths.add(width);
                    continue;
                }
                // 比原来大，更新数据
                if (width > widths.get(i)) {
                    widths.set(i, width);
                }
            }
            rowindex++;
        }
        // 设置列宽
        for (int index = 0; index < widths.size(); index++) {
            Integer width = widths.get(index);
            width = width < 2500 ? 2500 : width + 300;
            width = width > 10000 ? 10000 + 300 : width + 300;
            sheet.setColumnWidth(index, width);
        }
    }
}
